package com.telecom.restaurant.controllor.manage;


import com.telecom.restaurant.constant.DataResultConstant;
import com.telecom.restaurant.constant.ManageThreadLocal;
import com.telecom.restaurant.dao.MenuDayToFoodDao;
import com.telecom.restaurant.domin.DataResult;
import com.telecom.restaurant.domin.MealMenuResult;
import com.telecom.restaurant.enums.MenuTypeEnum;
import com.telecom.restaurant.model.MenuDayPO;
import com.telecom.restaurant.model.MenuDayToFoodPO;
import com.telecom.restaurant.model.param.MenuSearchParam;
import com.telecom.restaurant.service.MenuService;
import com.telecom.restaurant.service.PictureService;
import com.telecom.restaurant.util.DateUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Date;

import static com.telecom.restaurant.constant.DefaultConstant.TEMP_EXCEL_PATH;

/**
 * Created by qiqi on 2019/12/3.
 */
@Controller
@RequestMapping("/restaurant/menu")
public class MenuController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private MenuService menuService;

    @Autowired
    private PictureService pictureService;


    @Autowired
    private MenuDayToFoodDao menuDayToFoodPODao;

    @RequestMapping("/getMenu")
    @ResponseBody
    public DataResult getMenu(String date, Integer type) {

        Date searchDate = null;
        if (StringUtils.isBlank(date) || (searchDate = DateUtil.convertString2Date(date)) == null) {
            return DataResultConstant.WRONG_PARAM;
        }
        if (type == null) {
            type = MenuTypeEnum.BREAKFAST.getCode();
        }

        Long restaurantId = ManageThreadLocal.restaurantId.get();

        MenuSearchParam param = new MenuSearchParam();
        param.setDate(searchDate);
        param.setRestaurantId(restaurantId);
        param.setType(type);

        MealMenuResult result = menuService.getMealMenuResult(param);
        pictureService.renderMenuFoodPicture(result.getPackageMain());
        pictureService.renderMenuFoodPicture(result.getPackageDish());
        pictureService.renderMenuFoodPicture(result.getOtherDish());
        pictureService.renderMenuFoodPicture(result.getOtherMain());

        DataResult dataResult = DataResultConstant.buildSuccessResult(result);
        return dataResult;
    }

    @RequestMapping("/addFoodToMenu")
    @ResponseBody
    public DataResult addFoodToMenu(Long menuId,
                                    String date, Integer type, Long foodId) {
        Date searchDate = null;
        if (menuId == null) {
            if (StringUtils.isBlank(date) || (searchDate = DateUtil.convertString2Date(date)) == null) {
                return DataResultConstant.WRONG_PARAM;
            }
            if (type == null) {
                return DataResultConstant.WRONG_PARAM;
            }
        }
        if (foodId == null) {
            return DataResultConstant.WRONG_PARAM;
        }

        if (menuId == null) {
            Long restaurantId = ManageThreadLocal.restaurantId.get();
            MenuSearchParam param = new MenuSearchParam();
            param.setDate(searchDate);
            param.setRestaurantId(restaurantId);
            param.setType(type);

            MenuDayPO menuDayPO = menuService.getOrInsertMenuDay(param);
            menuId = menuDayPO.getId();
        }

        MenuDayToFoodPO menuDayToFoodPO = new MenuDayToFoodPO();
        menuDayToFoodPO.setCount(1);
        menuDayToFoodPO.setFoodId(foodId);
        menuDayToFoodPO.setMenuDayId(menuId);

        menuService.updateCache(menuId);

        try {
            menuDayToFoodPODao.insert(menuDayToFoodPO);
        } catch (Exception e) {
            logger.error("addFoodToMenu error. param:{}", menuDayToFoodPO, e);
        }

        DataResult dataResult = DataResultConstant.buildSuccessResult(null);
        return dataResult;
    }

    @RequestMapping("/setFoodStock")
    @ResponseBody
    public DataResult setFoodStock(Long menuId, Long foodId, Integer stock) {
        if (menuId == null || foodId == null || stock == null || stock <= 0) {
            return DataResultConstant.WRONG_PARAM;
        }
        MenuDayToFoodPO menuDayToFoodPO = new MenuDayToFoodPO();
        menuDayToFoodPO.setFoodId(foodId);
        menuDayToFoodPO.setMenuDayId(menuId);
        menuDayToFoodPO.setCount(stock);

        menuDayToFoodPODao.updateByPrimaryKeySelective(menuDayToFoodPO);

        DataResult dataResult = DataResultConstant.buildSuccessResult(null);
        return dataResult;
    }

    @RequestMapping("/removeFood")
    @ResponseBody
    public DataResult removeFood(Long menuId, Long foodId) {
        if (menuId == null || foodId == null) {
            return DataResultConstant.WRONG_PARAM;
        }

        menuDayToFoodPODao.deleteByMenuIdAndFoodId(menuId, foodId);
        menuService.updateCache(menuId);

        DataResult dataResult = DataResultConstant.buildSuccessResult(null);
        return dataResult;
    }

    @RequestMapping("/importMenu")
    @ResponseBody
    public DataResult importMenu(@RequestParam("file") MultipartFile file) {

        // 随机产生文件名
        String fileName = file.getOriginalFilename();

        try {
            File filePath = new File(TEMP_EXCEL_PATH);
            if (!filePath.exists()) {
                filePath.mkdir();
            }

            String newFilePath = TEMP_EXCEL_PATH + File.separator + System.currentTimeMillis() + "_" + fileName;
            File newFile = new File(newFilePath);
            logger.info("update excel path to {}", newFile.getAbsoluteFile());
            file.transferTo(newFile);

            menuService.importExcelMenu(newFile);

        } catch (Exception e) {
            logger.error("uploadImg error", e);
        }
        DataResult dataResult = DataResultConstant.buildSuccessResult(null);
        return dataResult;
    }


}
